/**
 * sessionStorage 和 localStorage 的2此封装
 * @param {string} type 存储方式：sessionStorage、localStorage
 * @returns {function} storage
 * @author gzq
 */

class Storage {
  constructor(type) {
    if (type === 'localStorage') {
      this.memory = window.localStorage;
    } else {
      this.memory = window.sessionStorage;
    }
  }
  /**
   * 设置缓存 
   * @param {object} params 
   * name: 键、value: 值、expired: 过期时间
   * @author gzq
   */
  setItem(name, value) {

    //判断一下value的类型
    const type = Object.prototype.toString.call(value);
    //如果value是对象或者数组对象的类型，就先用JSON.stringify转一下，再存进去
    if (type === '[object Object]' || type === '[object Array]') {
      // this.memory.setItem(Sm4encrypt(name), Sm4encrypt(JSON.stringify(value)));
      this.memory.setItem(name, JSON.stringify(value));
      return
    }
    // this.memory.setItem(Sm4encrypt(name), Sm4encrypt(value));
    this.memory.setItem(name, value);
  }
  /**
   * 取值
   * @param {string} name 键
   * @author gzq
   */
  getItem(name) {
    // let item = this.memory.getItem(name);
    // let item = this.memory.getItem(Sm4encrypt(name));
    let item = this.memory.getItem(name);
    if (!item || item == 'null' || item == 'undefined') {
      return null;
    }
    //先将拿到的试着进行json转为对象的形式
    try {
      // item = JSON.parse(Sm4Dncrypt(item));
      item = JSON.parse(item);
    } catch (error) {
      //如果不行就不是json的字符串，就直接返回
      // item = Sm4Dncrypt(item);
      item = item;
    }
      return item;
  }
  /**
   * 移除缓存
   * @param {string} name 键
   * @author gzq
   */
  removeItem(name) {
    // this.memory.removeItem(Sm4Dncrypt(name));
    this.memory.removeItem(name);
  }
  /**
   * 移除全部缓存
   * @param {string} name 键
   * @author gzq
   */
  clear() {
    this.memory.clear();
  }
}

const localMemory = new Storage('localStorage');
const sessionMemory = new Storage('sessionStorage');
export {
  localMemory,
  sessionMemory
}